<?php
/**
 * This file is part of workerman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link http://www.workerman.net/
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */

/**
 * 用于检测业务代码死循环或者长时间阻塞等问题
 * 如果发现业务卡死，可以将下面declare打开（去掉//注释），并执行php start.php reload
 * 然后观察一段时间workerman.log看是否有process_timeout异常
 */
//declare(ticks=1);

/**
 * 主逻辑
 * 主要是处理 onMessage onClose 
 */
use \GatewayWorker\Lib\Gateway;

class Events
{
   
   /**
    * coinClient      {"flag":"r","event":"broadcast","topic":"coin","data":{"bitcoin":"3585.20721025"}}
    * webClient       {"event":"subscribe","topic":"coin"}  {"event":"unsubscribe","topic":"coin"}
    * exchangeClient  {"flag":"r","event":"broadcast","topic":"exchange","name":"binance","data":{"bitcoin":"3585.20721025"}}
    * webClient       {"event":"subscribe","topic":"exchange","name":"binance"}  {"event":"unsubscribe","topic":"exchange","name":"binance"}
    * @param int $con
    * @param mixed $message
    * @return mixed
    */
    public static function onMessage($con, $message)
    {
        /*echo "received: $data\n";
        foreach ($ws->connections as $client) {
            $client->send('broadcast');
        }*/
        $data = json_decode($message, true);
        if (!$data) return false;
        // debug
        if (isset($data['debug'])) {
            echo "client:{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']} gateway:{$_SERVER['GATEWAY_ADDR']}:{$_SERVER['GATEWAY_PORT']}  client_id:$con session:".json_encode($_SESSION)." onMessage:".$message."\n";
        }
        switch ($data['event']) {
            case 'ping':
                $con->send('pong');
                break;
            case 'pong':
                break;
            case 'broadcast':
                if (!Utils::isFromRemoteClient($data)) return false;
                if (!Utils::subscribeValid($data)) return false;
                if (!Utils::isValidData($data)) return false;
                /*$msg = json_encode($data['data']);
                foreach ($ws->connections as $client) {
                    $client->send($msg);
                }*/
                $group = Utils::getGroupName($data);
                $msg = MessageHandler::handle($data);
                Gateway::sendToGroup($group, $msg);
                break;
            case 'subscribe':
                if (!Utils::subscribeValid($data)) return false;
                $group = Utils::getGroupName($data);
                Gateway::joinGroup($con, $group);
                break;
            case 'unsubscribe':
                if (!Utils::subscribeValid($data)) return false;
                $group = Utils::getGroupName($data);
                Gateway::leaveGroup($con, $group);
                break;
        }
    }
   
   /**
    * 当客户端断开连接时
    * @param integer $con 客户端id
    */
    public static function onClose($con)
    {
        // debug
        echo "client:{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']} gateway:{$_SERVER['GATEWAY_ADDR']}:{$_SERVER['GATEWAY_PORT']}  client_id:$con onClose:''\n";

        //$con->close();
    }
  
}
